import React, { Component } from 'react'
import { Form, Input, Button, message} from 'antd';
//引入登录请求方法
import {userLogin} from "@api"
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
}

export default class Login extends Component {
  render() {
    return (
      <div className="login">
         <Form
              {...layout}
              name="basic"
              initialValues={{ remember: true }}
              onFinish={this.login}
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: 'Please input your username!' }]}
              >
                <Input placeholder="请输入用户名"/>
              </Form.Item>

              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: 'Please input your password!' }]}
              >
                <Input.Password placeholder="请输入密码"/>
              </Form.Item>
              <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit">
                  登录
                </Button>
              </Form.Item>
        </Form>
        
      </div>
    )
  }
  login=(value)=>{
   //假设登录成功，数据直接返回
   userLogin(value).then(res=>{
     if(res.data.code==="0"){
       //利用message弹出提示
       message.success(res.data.msg,2,()=>{
         //处理存储问题
         localStorage.setItem("accessToken",res.data.data.token)
         localStorage.setItem("userInfo",JSON.stringify({
          userName:res.data.data.userName,
          avatar:res.data.data.avatar,
          role:res.data.data.role
        }))
         //登录成功后，判断要去哪
         if(this.props.location.state){
           //去指定的路径页面
           this.props.history.push(this.props.location.state.form)
         }else{
           //去admin页面
           this.props.history.push("/admin")
         }  
       })
     }
   })
  }
}
